import { populateFormData, populateArrayFormData } from "../../utils/util";
import { http } from "../../utils/http"
export default {
    addToCart({ commit }, payload) {
        commit('addCartItem', payload)
    },
    addToBuyNow(ctx, payload) {
        const params = populateFormData(payload.cartItem);
        http.post("/order/buyGoods", params).then(
            (resp) => {
                if (resp.data.code == 0) {
                    ctx.commit('addToBuyNow', payload.cartItem);
                    payload.success()
                } else {
                    payload.fail()
                }
            }
        )
    },
    deleteCartItem({ commit }, item) {
        commit('deleteCartItem', item);
    },
    clearCartItems({ commit }) {
        commit('clearCartItems')
    },
    toCheckout(ctx, payload) {
        const params = populateArrayFormData(ctx.state.cartItems);
        http.post("/order/buyGoods", params).then(
            (resp) => {
                if (resp.data.code == 0) {
                    payload.success()
                } else {
                    payload.fail()
                }
            },
        )
    },
    checkout({ commit }, payload) {
        const params = populateFormData(payload.data);
        console.log(payload.data)
        http.post("/order/addOrder", params).then(
            (resp) => {
                if (resp.data.code == 0) {
                    //处理的是购物车数据
                    if (payload.type === 'cart') {
                        commit('clearCartItems');
                    } else if (payload.type == 'now') {
                        commit('clearBuyNow')
                    }
                    payload.success(resp.data.orderId)
                } else {
                    payload.fail()
                }
            },
        )
    },
    fetchMyOrders({ commit }) {
        http.get("/order/getMyOrders").then(
            (resp) => {
                if (resp.data.code == 0) {
                    commit('saveMyOrders', resp.data.orders);
                }
            },
        )
    }
}